<template>
  <div class="canvas">
    <div class="item" v-for="(item, index) in list" :key="index">
      <span>{{ item.result }}</span>
    </div>

    <el-button type="primary" plain @click="add">主要按钮</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [
        {
          endTime: Date.now() + 10 * 1000,
          timer: null,
          result: null,
        },
        {
          endTime: Date.now() + 20 * 1000,
          timer: null,
          result: null,
        },
      ],

      addOperate: false,
    };
  },
  computed: {},
  mounted() {
    this.startCountdown();
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    /**
     * 启动倒计时定时器
     */
    startCountdown() {
      let that = this;
      that.list.forEach((item) => {
        item.timer = setInterval(() => {
          // 触发计算属性重新计算
          const now = Date.now();
          const diff = item.endTime - now;
          if (diff <= 1000) {
            clearInterval(item.timer);
            that.$set(item, "result", "倒计时结束");
            return;
          }
          that.$set(item, "result", that.formatTime(diff));
        }, 1000);
      });
    },
    /**
     * 将时间差值格式化为易读的时间字符串
     * @param {number} diff 时间差值，单位为毫秒
     * @returns {string} 格式化后的时间字符串
     */
    formatTime(diff) {
      const totalSeconds = Math.floor(diff / 1000);
      const days = Math.floor(totalSeconds / (3600 * 24));
      const hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      const seconds = totalSeconds % 60;

      // 补零操作
      const paddedDay = String(days).padStart(2, "0");
      const paddedHours = String(hours).padStart(2, "0");
      const paddedMinutes = String(minutes).padStart(2, "0");
      const paddedSeconds = String(seconds).padStart(2, "0");
      return `${paddedDay} 天 ${paddedHours} 时 ${paddedMinutes} 分 ${paddedSeconds} 秒`;
    },

    add() {
      this.list.push({
        endTime: Date.now() + 10 * 1000,
        timer: null,
        result: null,
      });
      this.list.map((item) => {
        if (item.timer) {
          clearInterval(item.timer);
        }
      });
      this.startCountdown();
    },
  },
};
</script>
<style lang="scss" scoped>
.canvas {
  display: grid;
  grid-template-columns: repeat(3, 200px);
  grid-template-rows: repeat(3, 200px);
  grid-gap: 10px;
}
.item {
  background-color: #f0f0f0;
}
</style>
